<?php
/**
 * 经纪人模型
 */

namespace app\badmin\model;


use app\common\lib\RespCode;
use app\common\model\BaseModel;
use custom\Err;
use custom\Log;
use custom\Redis;
use oss\Oss;
use think\Db;
use think\Exception;

class CompanyAgent extends BaseModel {

    /**
     * 编辑经济人
     * @param $params
     * @return bool
     */
    public static function post($params) {
        if (!empty($params['id'])) {
            //编辑
            if ($params['account_type'] != 0) {//门店账号
                $old = db("company_agent")
                    ->where('id', $params['id'])
                    ->where('deleted', 0)
                    ->where('company_shop_id', $params['company_shop_id'])
                    ->find();
            } else {
                $old = db("company_agent")
                    ->where('deleted', 0)
                    ->where('id', $params['id'])
                    ->find();
            }
            if (empty($old)) {
                Err::add('数据不存在', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (empty($params['id'])) {
            $has_phone = db("company_agent")->where('phone', $params['phone'])->select();
            if ($has_phone) {
                Err::add('电话已被注册', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (!empty($params['shop_id'])) {//选择了门店
            $hasShop = db("company_shop")
                ->where('deleted', 0)
                ->where('id', $params['shop_id'])
                ->find();
            if (empty($hasShop)) {
                Err::add('门店不存在', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (preg_match("/^([\x{4e00}-\x{9fa5}]|\w){1,15}$/u", trim($params['name'])) == false) {
            Err::add('经纪人姓名：15长度，数字、字母、汉字、下划线', RespCode::PARAMS_ERR);
            return false;
        }
        if (preg_match("/^([\x{4e00}-\x{9fa5}]|\w){1,15}$/u", trim($params['position'])) == false) {
            Err::add('经纪人职位：15长度，数字、字母、汉字、下划线', RespCode::PARAMS_ERR);
            return false;
        }
        if(empty($params['id'])){
            if (!preg_match('/^1[3-9]\d{9}$/', $params['phone'])) {
                Err::add('电话号码不正确', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (!empty($params['wechat'])) {
            if (mb_strlen(trim($params['wechat']), 'utf-8') < 5 || mb_strlen(trim($params['wechat']), 'utf-8') > 20) {
                Err::add('微信号长度限制5至20位', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if ($params['account_type'] == 0) {//公司账号
            if (empty($params['id'])) {//添加
                $company_shop_id = $params['shop_id'];
            } else { //编辑
                $company_shop_id = $params['shop_id'];
            }
        } else {
            $company_shop_id = $params['company_shop_id'];
        }
        $data = [
            'company_id'      => $params['company_id'],
            'company_shop_id' => $company_shop_id,
            'name'            => trim($params['name']),
            'phone'           => $params['phone'],
            'position'        => $params['position'],
            'address'         => $params['address'],
            'wechat'          => empty($params['wechat']) ? "" : $params['wechat'],
            'cover'           => empty($params['cover']) ? "" : $params['cover'],
            'email'           => '',
            'itime'           => time(),
            'utime'           => time(),
            //            'wechat_code'     => 1,
        ];
        if (empty($params['id'])) {//添加
            //设置客服
            $customer = db("company_agent")
                ->where('company_id', $params['company_id'])
                ->where('is_customer', 1)
                ->select();
            if (empty($customer)) {
                $data['is_customer'] = 1;
            }

            Db::startTrans();
            if ($company_shop_id != 0) {//选择了门店
                $shop = CompanyShop::getOne([['id', '=', $company_shop_id]], 'lave_num');
                if ($shop['lave_num'] < 1) {
                    Err::add('门店剩余可添加经纪人数不足', RespCode::PARAMS_ERR);
                    return false;
                }
                $status1 = CompanyShop::lessAgent($company_shop_id, 1);
                if (!$status1) {
                    Db::rollback();
                    Err::add('操作失败，请稍后尝试', RespCode::DATA_ERR);
                    return false;
                }
            } else {
                //选择了直属公司
                $company = Company::getOne([['id', '=', $params['company_id']]], 'lave_num');
                if ($company['lave_num'] < 1) {
                    Err::add('公司剩余可添加经纪人数不足', RespCode::PARAMS_ERR);
                    return false;
                }
                //扣直属公司的剩余人数
                $status1 = Company::lessAgentNum(1, $params['company_id']);
                if (!$status1) {
                    Db::rollback();
                    Err::add('操作失败，请稍后尝试', RespCode::DATA_ERR);
                    return false;
                }
            }
            $data['template_id'] = 1;
            $insertId = self::insertGetId($data);
            if (!$insertId) {
                Db::rollback();
                Err::add('操作失败，请稍后尝试', RespCode::DATA_ERR);
                return false;
            }
            //生成经纪人名片二维码
            self::createWechatCode($params, $insertId, $code, $url, 'pages/index/index');
            if (!$code) {
                Db::rollback();
                Err::add('错误的appid和secret', RespCode::DATA_ERR);
                return false;
            }
            if (!self::where('id', $insertId)->update(['wechat_code' => $url])) {
                Db::rollback();
                Err::add('操作失败，请稍后尝试', RespCode::DATA_ERR);
                return false;
            }
            //修改公司的auto_house_url
            if (empty($customer)) {
                self::createWechatCode($params, $insertId, $code2, $url2, 'pages/submit/demand');
                if (!$code2) {
                    Db::rollback();
                    Err::add('错误的appid和secret', RespCode::DATA_ERR);
                    return false;
                }
                if (!Company::getAutoHouseUrl($url2, $params['company_id'])) {
                    Db::rollback();
                    Err::add('操作失败，请稍后尝试', RespCode::DATA_ERR);
                    return false;
                }
            }
            Db::commit();
            return $code;
        } else {//修改操作
            unset($data['phone']);
            Db::startTrans();
            //删除图片
            if ($old['cover'] != $params['cover'] && !empty($old['cover'])) {
                $oss = Oss::getInstance();
                $oss->delOneFile($old['cover']);
            }
            if ($company_shop_id != $old['company_shop_id']) {//更换了门店
                if ($company_shop_id == 0) {//选择了公司
                    $company = Company::getOne([['id', '=', $params['company_id']]], 'lave_num');
                    if ($company['lave_num'] < 1) {
                        Err::add('公司剩余可添加经纪人数不足', RespCode::PARAMS_ERR);
                        return false;
                    }
                    $re1 = Company::lessAgentNum(1, $params['company_id']);//对应公司减一
                    if (!$re1) {
                        Db::rollback();
                        Err::add('操作失败，请稍后尝试', RespCode::DATA_ERR);
                        return false;
                    }
                    if ($old['company_shop_id'] == 0) {//之前是公司直属
                        $re2 = Company::addAgentNum(1, $params['company_id']);
                        if (!$re2) {
                            Db::rollback();
                            Err::add('操作失败，请稍后尝试', RespCode::DATA_ERR);
                            return false;
                        }
                    } else {//之前是门店
                        $re2 = CompanyShop::addAgent($old['company_shop_id'], 1);
                        if (!$re2) {
                            Db::rollback();
                            Err::add('操作失败，请稍后尝试', RespCode::DATA_ERR);
                            return false;
                        }
                    }
                } else {//选择了门店
                    $companyshop = CompanyShop::getOne([['id', '=', $company_shop_id]], 'lave_num');
                    if ($companyshop['lave_num'] < 1) {
                        Err::add('选择的门店剩余经纪人数不足1', RespCode::PARAMS_ERR);
                        return false;
                    }
                    $re1 = CompanyShop::lessAgent($company_shop_id, 1);//对应门店减一
                    if (!$re1) {
                        Db::rollback();
                        Err::add('操作失败，请稍后尝试', RespCode::DATA_ERR);
                        return false;
                    }

                    if ($old['company_shop_id'] == 0) {//之前是公司直属
                        $re2 = Company::addAgentNum(1, $params['company_id']);
                        if (!$re2) {
                            Db::rollback();
                            Err::add('操作失败，请稍后尝试', RespCode::DATA_ERR);
                            return false;
                        }
                    } else {//之前是门店
                        $re2 = CompanyShop::addAgent($old['company_shop_id'], 1);
                        if (!$re2) {
                            Db::rollback();
                            Err::add('操作失败，请稍后尝试', RespCode::DATA_ERR);
                            return false;
                        }
                    }
                }
            }
            self::where('id', $params['id'])->update($data);
            db('company_agent_user')->where('agent_id', $params['id'])->update(['company_shop_id' => $data['company_shop_id']]);
            Db::commit();
            return true;
        }
    }

    /**
     * 经纪人列表
     * @param $params
     * @return array
     */
    public static function getList($params) {
        empty($params['page']) ? $page = 1 : $page = $params['page'];
        empty($params['long']) ? $long = 10 : $long = $params['long'];
        $column = ['ca.id', 'ca.phone', 'ca.name', 'ca.position', 'ca.cover', 'ca.address', 'ca.itime', 'ch.name as ch_name'];
        $order = ['ca.id' => 'desc'];
        $whereRaw = ' if(ca.company_shop_id=0,c.deleted = 0,ch.deleted = 0)';
        $map[] = ['ca.deleted', '=', 0];
        if ($params['account_type'] == 0) {//公司账号
            if (isset($params['shop_id']) && $params['shop_id'] != '') {
                $map[] = ['ca.company_shop_id', '=', $params['shop_id']];
                $map[] = ['ca.company_id', '=', $params['company_id']];
            } else {
                $map[] = ['ca.company_id', '=', $params['company_id']];
            }
        }
        if ($params['account_type'] == 1) {//门店账号
            $map[] = ['ca.company_shop_id', '=', $params['company_shop_id']];
        }
        //经纪人名
        if (!empty($params['ca_name'])) {
            $map[] = ['ca.name', 'like', '%' . trim($params['ca_name']) . '%'];
        }
        $data = self::list_query($map, $whereRaw, $page, $long, $column, $order);
        foreach ($data['data'] as $k => $v) {
            $data['data'][$k]['itime'] = date('Y-m-d H:i', $v['itime']);
            $data['data'][$k]['ch_name'] = empty($data['data'][$k]['ch_name']) ? "直属公司" : $data['data'][$k]['ch_name'];
        }
        return $data;
    }

    /**
     * 列表sql
     * @param $map
     * @param $page
     * @param $long
     * @param $column
     * @param $order
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function list_query($map, $whereRaw, $page, $long, $column, $order) {
        $count = db("company_agent")
            ->alias('ca')
            ->leftJoin('company_shop ch', 'ch.id = ca.company_shop_id')
            ->leftJoin('company c', 'c.id = ca.company_id')
            ->where($map)
            ->whereRaw($whereRaw)
            ->count();
        if ($count == 0) {
            $result = [
                'page'    => 1,
                'pageNum' => 1,
                'count'   => 0,
                'data'    => [],
            ];
            return $result;
        } else {
            $data = db("company_agent")
                ->alias('ca')
                ->leftJoin('company_shop ch', 'ch.id = ca.company_shop_id')
                ->leftJoin('company c', 'c.id = ca.company_id')
                ->where($map)
                ->whereRaw($whereRaw)
                ->page($page, $long)
                ->field($column)
                ->order($order)
                ->select();
            $pageNum = ceil($count / $long);
            $result = [
                'page'    => (int)$page,
                'pageNum' => $pageNum,
                'count'   => $count,
                'data'    => $data,
            ];
            return $result;
        }
    }

    /**
     * 获取编辑信息
     * @param $params
     * @return array|bool|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getInfo($params) {
        $data = db("company_agent")
            ->alias('ca')
            ->leftjoin('company_shop cs', 'cs.id = ca.company_shop_id')
            ->where('ca.id', $params['id'])
            ->where('ca.deleted', 0)
            ->where('ca.company_id', $params['company_id'])
            ->field('ca.name,ca.phone,ca.position,ca.address,ca.wechat,ca.cover,ca.company_shop_id,cs.name as cs_name')
            ->find();
        $data['cs_name'] = empty($data['cs_name']) ? "直属公司" : $data['cs_name'];
        if (empty($data)) {
            Err::add('数据不存在', RespCode::PARAMS_ERR);
            return false;
        }
        return $data;
    }

    /**
     * 门店下面的经纪人
     * @param $params
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function hasAgent($params) {
        $data = db("company_agent")
            ->where('company_shop_id', $params['id'])
            ->where('company_id', $params['company_id'])
            ->select();
        if ($data) {
            Err::add('门店有关联经纪人，不能删除', RespCode::PARAMS_ERR);
            return false;
        }
    }

    /**
     * 客服
     * @param $params
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getKefu($params) {
        $data = db('company_agent')
            ->where('is_customer', 1)
            ->where('company_id', $params['company_id'])
            ->field('id')
            ->find();
        if (empty($data)) {
            Err::add('该公司未添加客服');
            return false;
        }
        return $data;
    }

    /**
     * 经纪人列表
     * @param $params
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function agentList($params) {
        return db("company_agent")
            ->where('company_id', $params['company_id'])
            ->where('deleted', 0)
            ->field('name,phone,id')
            ->select();
    }

    /**
     * 设置客服
     * @param $params
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public static function setKefu($params) {
        if (empty(db('company_agent')->where('deleted', 0)->find($params['id']))) {
            Err::add('经纪人不存在', RespCode::PARAMS_ERR);
            return false;
        }
        if ($params['account_type'] != 0) {
            Err::add('当前账号类型不是公司账号', RespCode::PARAMS_ERR);
            return false;
        }
        Db::startTrans();
        if (!db("company_agent")
            ->where('company_id', $params['company_id'])
            ->where('is_customer', 1)
            ->update(['is_customer' => 0])) {
            Db::rollback();
            Err::add('操作失败，稍后尝试', RespCode::PARAMS_ERR);
            return false;
        }
        if (!db("company_agent")
            ->where('company_id', $params['company_id'])
            ->where('id', $params['id'])
            ->update(['is_customer' => 1])) {
            Db::rollback();
            Err::add('操作失败，稍后尝试', RespCode::PARAMS_ERR);
            return false;
        }
        self::createWechatCode($params, $params['id'], $code, $url, 'pages/submit/demand');
        if (!$code) {
            Db::rollback();
            Err::add('错误的appid和secret', RespCode::DATA_ERR);
            return false;
        }
        if (!Company::getAutoHouseUrl($url, $params['company_id'])) {
            Db::rollback();
            Err::add('操作失败，稍后尝试', RespCode::PARAMS_ERR);
            return false;
        }
        Db::commit();
        return true;
    }

    /**
     * 生成二维码
     */
    public static function createWechatCode($params, $id, &$code, &$url, $to_path) {
        $code = true;
        $url = '';
        $company = Company::getOne([['id', '=', $params['company_id']]], 'appid,secret');
        $appid = $company['appid'];
        $secret = $company['secret'];
        $grant_type = 'client_credential';

        $redis = Redis::getInstance();
        $ACCESS_TOKEN = $redis->get('badmin_agent_createWechatCode');
        if ($ACCESS_TOKEN === false) {
            $uri = "https://api.weixin.qq.com/cgi-bin/token?grant_type={$grant_type}&appid={$appid}&secret={$secret}";
            $json_data = self::httpRequest($uri);
            $json_data = json_decode($json_data, true);
            if (!isset($json_data['access_token'])) {
                $code = false;
                return;
            }
            $ACCESS_TOKEN = $json_data["access_token"];
            $redis->setex('badmin_agent_createWechatCode', 7200, $ACCESS_TOKEN);
        }

        $qcode = "https://api.weixin.qq.com/wxa/getwxacode?access_token={$ACCESS_TOKEN}";
        $param = json_encode(array("path" => "{$to_path}?agent_id={$id}", "width" => 150));
        $result = self::httpRequest($qcode, $param, "POST");//文件流
        $oss = Oss::getInstance();
        $url = $oss->createFilename("badmin/createWechatCode", 'jpeg');
        if ($oss->putObject($result)) {
            $redisModel = Redis::getInstance();
            $redisModel->hset('upload_file', date('Y-m-d'), "badmin/createWechatCode");
        }
    }

    /**
     * http请求
     * @param $url
     * @param string $data
     * @param string $method
     * @return bool|string
     */
    public static function httpRequest($url, $data = '', $method = 'GET') {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        if ($method == 'POST') {
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data != '') {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
        }
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }

    /**
     * 可移交经纪人列表
     * @param $params
     * @return array|\PDOStatement|string|\think\Collection
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function transfer($params) {
        $company_agent = db("company_agent")
            ->where('deleted', 0)
            ->where('id', $params['id'])
            ->find();
        if (empty($company_agent)) {
            Err::add('经纪人不存在', RespCode::PARAMS_ERR);
            return false;
        }
        if ($company_agent['is_customer'] == 1) {
            Err::add('不可删除原因:该经纪人是默认客服', RespCode::PARAMS_ERR);
            return false;
        }
        if ($params['account_type'] == 0) {//公司账号
            $data = db("company_agent")
                ->where('company_id', $params['company_id'])
                ->where('company_shop_id', $company_agent['company_shop_id'])
                ->where('id', '<>', $params['id'])
                ->where('deleted', 0)
                ->field('name,id')
                ->select();
            if (empty($data)) {
                Err::add('不可删除原因：该公司没有可以移交经纪人', RespCode::PARAMS_ERR);
                return false;
            }
        } else {
            $data = db("company_agent")
                ->where('company_id', $params['company_id'])
                ->where('company_shop_id', $params['company_shop_id'])
                ->where('id', '<>', $params['id'])
                ->where('deleted', 0)
                ->field('name,id')
                ->select();
            if (empty($data)) {
                Err::add('不可删除原因：该门店没有可以移交经纪人', RespCode::PARAMS_ERR);
                return false;
            }
        }
        return $data;
    }

    /**
     * 删除经济人
     * @param $params
     * @return bool
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function del($params) {
        Db::startTrans();
        if (db("company_agent")->where('id', $params['id'])->value('is_customer') == 1) {
            Err::add('不可删除原因:该经纪人是默认客服', RespCode::PARAMS_ERR);
            return false;
        }
        if (intval($params['id']) == intval($params['new_id'])) {
            Err::add('删除对象和移交对象重复', RespCode::PARAMS_ERR);
            return false;
        }

        $company_agent_info1 = db("company_agent")
            ->where('id', $params['id'])
            ->find();
        $company_agent_info2 = db("company_agent")
            ->where('id', $params['new_id'])
            ->find();

        if ($company_agent_info1['deleted'] == 1 || $company_agent_info2['deleted'] == 1) throw new Exception('经纪人不存在', RespCode::PARAMS_ERR);

        if ($company_agent_info1['company_shop_id'] != $company_agent_info2['company_shop_id']) throw new Exception('删除对象和转移对象需在同一门店', RespCode::PARAMS_ERR);

        //被删除经纪人的关联数据
        $beishan_company_agent_user = db("company_agent_user")
            ->where('agent_id', $params['id'])
            ->fieldRaw('concat(status,"_",user_id) as status_userid,status,user_id')
            ->select();
        $beishan_company_agent_user_user_id_array = array_column($beishan_company_agent_user, 'user_id');
        //新经纪人的关联数据
        $new_company_agent_user = db("company_agent_user")
            ->where('agent_id', $params['new_id'])
            ->fieldRaw('concat(status,"_",user_id) as status_userid,status,user_id')
            ->select();
        $new_company_agent_user_user_id_array = array_column($new_company_agent_user, 'user_id');
        $Intersection = [];//交集用户user_id
        foreach ($beishan_company_agent_user as $k1 => $v1) {
            //两人拥有的相同用户user_id集
            if (in_array($beishan_company_agent_user[$k1]['user_id'], $new_company_agent_user_user_id_array)) {
                $Intersection[] = $beishan_company_agent_user[$k1]['user_id'];
            }
        }
        /**
         * 处理company_agent_user 经纪人用户关系表
         */
        if (!empty($Intersection)) {
            //循环交集用户 id
            foreach ($Intersection as $k2 => $v2) {
                //该用户对应被删除经纪人那的资料
                $beishan_company_agent_user = db("company_agent_user")
                    ->where('user_id', $Intersection[$k2])
                    ->where('agent_id', $params['id'])
                    ->find();
                //该用户对应移交经纪人的资料
                $new_company_agent_user = db("company_agent_user")
                    ->where('user_id', $Intersection[$k2])
                    ->where('agent_id', $params['new_id'])
                    ->find();
                //专属 转 非专属 以专属为准
                if ($beishan_company_agent_user['status'] == 2 && $new_company_agent_user['status'] == 1) {
                    //更新 该用户在 移交经纪人 的那状态，并更新用户信息字段
                    if ($beishan_company_agent_user['is_like'] == 1 || $new_company_agent_user['is_like'] == 1) $is_like = 1;
                    else $is_like = 0;
                    $new_old_agent_id = $new_company_agent_user['old_agent_id'];
                    if ($new_old_agent_id) {
                        $new_old_agent_id = explode(',', $new_old_agent_id);
                        $new_old_agent_id[] = $params['id'];
                        $new_old_agent_id = join(',', $new_old_agent_id);
                    } else $new_old_agent_id = $params['id'];
                    $new_info = [
                        'status'            => $beishan_company_agent_user['status'],
                        'num'               => $beishan_company_agent_user['num'] + $new_company_agent_user['num'],
                        'phone'             => $beishan_company_agent_user['phone'],
                        'remark_phone'      => $beishan_company_agent_user['remark_phone'],
                        'company'           => $beishan_company_agent_user['company'],
                        'position'          => $beishan_company_agent_user['position'],
                        'province'          => $beishan_company_agent_user['province'],
                        'city'              => $beishan_company_agent_user['city'],
                        'area'              => $beishan_company_agent_user['area'],
                        'birthday'          => $beishan_company_agent_user['birthday'],
                        'remark'            => $beishan_company_agent_user['remark'],
                        'recommend_house'   => $beishan_company_agent_user['recommend_house'],
                        'is_demand'         => $beishan_company_agent_user['is_demand'],
                        'itime_exclusive'   => time(),
                        'daytime_exclusive' => strtotime(date('Y-m-d', time())),
                        'is_like'           => $is_like,
                        'old_agent_id'      => $new_old_agent_id
                    ];

                    if (!db("company_agent_user")
                        ->where('agent_id', $params['new_id'])
                        ->where('user_id', $Intersection[$k2])
                        ->update($new_info)) {
                        Db::rollback();
                        Err::add('操作失败请稍后尝试', RespCode::QUERY_ERR);
                        Log::write("更新失败company_agent_user->" . __LINE__, 'del_agent.log');
                        return false;
                    }

                    /**
                     * 需求转移
                     */
                    db("agent_user_demand")
                        ->where("agent_id", $params['id'])
                        ->update(['agent_id' => $params['new_id']]);
                }
                //专属 转 专属 基本不动
                if ($beishan_company_agent_user['status'] == 2 && $new_company_agent_user['status'] == 2) goto zhuanTozhuan;
                //非专属 转 专属 基本不动
                if ($beishan_company_agent_user['status'] == 1 && $new_company_agent_user['status'] == 2) {
                    zhuanTozhuan:
                    //移交互动次数
                    $new_info['num'] = $beishan_company_agent_user['num'] + $new_company_agent_user['num'];
                    //有一方点赞就是点了赞
                    if ($beishan_company_agent_user['is_like'] == 1 || $new_company_agent_user['is_like'] == 1) {
                        $new_info['is_like'] = 1;
                    } else {
                        $new_info['is_like'] = 0;
                    }
                    $new_old_agent_id = $new_company_agent_user['old_agent_id'];
                    if ($new_old_agent_id) {
                        $new_old_agent_id = explode(',', $new_old_agent_id);
                        $new_old_agent_id[] = $params['id'];
                        $new_old_agent_id = join(',', $new_old_agent_id);
                    } else {
                        $new_old_agent_id = $params['id'];
                    }
                    $new_info['old_agent_id'] = $new_old_agent_id;
                    //更新 该用户在 移交经纪人 的那状态，并更新用户信息字段
                    if (!db("company_agent_user")
                        ->where('agent_id', $params['new_id'])
                        ->where('user_id', $Intersection[$k2])
                        ->update($new_info)) {
                        Db::rollback();
                        Err::add('操作失败请稍后尝试', RespCode::QUERY_ERR);
                        Log::write("更新失败company_agent_user->" . __LINE__, 'del_agent.log');
                        return false;
                    }
                }
                //非专属 转 非专属 以数据多的为准
                if ($beishan_company_agent_user['status'] == 1 && $new_company_agent_user['status'] == 1) {
                    $new_info['num'] = $beishan_company_agent_user['num'] + $new_company_agent_user['num'];
                    $new_info['phone'] = empty($new_company_agent_user['phone']) ? $beishan_company_agent_user['phone'] : $new_company_agent_user['phone'];
                    $new_info['remark_phone'] = empty($new_company_agent_user['remark_phone']) ? $beishan_company_agent_user['remark_phone'] : $new_company_agent_user['remark_phone'];
                    $new_info['company'] = empty($new_company_agent_user['company']) ? $beishan_company_agent_user['company'] : $new_company_agent_user['company'];
                    $new_info['position'] = empty($new_company_agent_user['position']) ? $beishan_company_agent_user['position'] : $new_company_agent_user['position'];
                    $new_info['province'] = empty($new_company_agent_user['province']) ? $beishan_company_agent_user['province'] : $new_company_agent_user['province'];
                    $new_info['city'] = empty($new_company_agent_user['city']) ? $beishan_company_agent_user['city'] : $new_company_agent_user['city'];
                    $new_info['area'] = empty($new_company_agent_user['area']) ? $beishan_company_agent_user['area'] : $new_company_agent_user['area'];
                    $new_info['birthday'] = empty($new_company_agent_user['birthday']) ? $beishan_company_agent_user['birthday'] : $new_company_agent_user['birthday'];
                    $new_info['remark'] = empty($new_company_agent_user['remark']) ? $beishan_company_agent_user['remark'] : $new_company_agent_user['remark'];
                    if ($beishan_company_agent_user['is_like'] == 1 || $new_company_agent_user['is_like'] == 1) {
                        $new_info['is_like'] = 1;
                    } else {
                        $new_info['is_like'] = 0;
                    }
                    $new_old_agent_id = $new_company_agent_user['old_agent_id'];
                    if ($new_old_agent_id) {
                        $new_old_agent_id = explode(',', $new_old_agent_id);
                        $new_old_agent_id[] = $params['id'];
                        $new_old_agent_id = join(',', $new_old_agent_id);
                    } else {
                        $new_old_agent_id = $params['id'];
                    }
                    $new_info['old_agent_id'] = $new_old_agent_id;
                    //更新 移交经纪人 的用户信息
                    if (!db("company_agent_user")
                        ->where('agent_id', $params['new_id'])
                        ->where('user_id', $Intersection[$k2])
                        ->update($new_info)) {
                        Db::rollback();
                        Err::add('操作失败请稍后尝试', RespCode::QUERY_ERR);
                        Log::write("更新失败company_agent_user->" . __LINE__, 'del_agent.log');
                        return false;
                    }
                }

                /**
                 * 更新agent_follow_log 跟进记录表
                 */
                //在被删除经纪人那是专属客户 才转移
                if ($beishan_company_agent_user['status'] == 2) {
                    $agent_follow_log = db('agent_follow_log')
                        ->where('agent_user_id', $beishan_company_agent_user['id'])
                        ->field('id,old_id')
                        ->find();
                    if ($agent_follow_log) {
                        if ($agent_follow_log['old_id']) {
                            $old_id = explode(',', $agent_follow_log['old_id']);
                            $old_id[] = $beishan_company_agent_user['id'];
                            $new_old_id = join(',', $old_id);
                        } else {
                            $new_old_id = $beishan_company_agent_user['id'];
                        }
                        if (!db('agent_follow_log')
                            ->where('agent_user_id', $beishan_company_agent_user['id'])
                            ->update(['agent_user_id' => $new_company_agent_user['id'], 'old_id' => $new_old_id])) {
                            Db::rollback();
                            Err::add('操作失败请稍后尝试', RespCode::QUERY_ERR);
                            Log::write("更新失败agent_follow_log->" . __LINE__, 'del_agent.log');
                            return false;
                        }
                    }
                }

                /**
                 * 更新agent_user_interaction_log 互动记录表
                 */
                if (db('agent_user_interaction_log')
                    ->where('agent_user_id', $beishan_company_agent_user['id'])
                    ->select()) {
                    if (!db('agent_user_interaction_log')
                        ->where('agent_user_id', $beishan_company_agent_user['id'])
                        ->update(['agent_user_id' => $new_company_agent_user['id']])) {
                        Db::rollback();
                        Err::add('操作失败请稍后尝试', RespCode::QUERY_ERR);
                        Log::write("更新失败agent_user_interaction_log->" . __LINE__, 'del_agent.log');
                        return false;
                    }
                }
            }
        }

        //新经纪人没有的user_id
        $noIntersection = array_merge(array_diff($beishan_company_agent_user_user_id_array, $Intersection));
        if ($noIntersection) {
            foreach ($noIntersection as $k3 => $v3) {
                //把 被删除经纪人的关系 变为 移交经纪人的关系
                $agent_user = db("company_agent_user")
                    ->where('agent_id', $params['id'])
                    ->where('user_id', $v3)
                    ->find();
                //此客户在被删除经纪人那是专属
                if ($agent_user['status'] == 2) {
                    if (!db("company_agent_user")
                        ->where('agent_id', $params['id'])
                        ->where('user_id', $v3)
                        ->update(['agent_id' => $params['new_id'], 'itime_exclusive' => time(), 'daytime_exclusive' => strtotime(date('Y-m-d', time()))])) {
                        Db::rollback();
                        Err::add('操作失败请稍后尝试', RespCode::QUERY_ERR);
                        Log::write("更新失败company_agent_user->" . __LINE__, 'del_agent.log');
                        return false;
                    }

                    /**
                     * 需求转移
                     */
                    db("agent_user_demand")
                        ->where("agent_id", $params['id'])
                        ->update(['agent_id' => $params['new_id']]);
                }
                //此客户在被删除经纪人那是潜在
                if ($agent_user['status'] == 1) {
                    if (!db("company_agent_user")
                        ->where('agent_id', $params['id'])
                        ->where('user_id', $v3)
                        ->update(['agent_id' => $params['new_id'], 'itime_potential' => time(), 'daytime_potential' => strtotime(date('Y-m-d', time()))])) {
                        Db::rollback();
                        Err::add('操作失败请稍后尝试', RespCode::QUERY_ERR);
                        Log::write("更新失败company_agent_user->" . __LINE__, 'del_agent.log');
                        return false;
                    }
                }
            }
        }


        /**
         * 处理company_user表
         */
        //目前关联被删除经纪人的用户
        $beishan_company_user = db("company_user")
            ->where('agent_id', $params['id'])
            ->field('old_agent_id,id')
            ->select();
        foreach ($beishan_company_user as $v4) {
            if ($v4['old_agent_id']) {
                $old_company_user = explode(',', $v4['old_agent_id']);
                $old_company_user[] = $params['id'];
                $new_old_agent_id = join(',', $old_company_user);
            } else {
                $new_old_agent_id = $params['id'];
            }
            //被删除经纪人的用户 关联到 移交经纪人
            if (!db("company_user")
                ->where('id', $v4['id'])
                ->update(['old_agent_id' => $new_old_agent_id, 'agent_id' => $params['new_id']])) {
                Db::rollback();
                Err::add('操作失败请稍后尝试', RespCode::QUERY_ERR);
                Log::write("更新失败company_user->" . __LINE__, 'del_agent.log');
                return false;
            }
        }

        //更新公司/门店 的 剩余经纪人数
        $_company_shop_id = db("company_agent")->where('id', $params['id'])->value('company_shop_id');
        if ($_company_shop_id == 0) {//公司
            if (!Company::addAgentNum(1, $params['company_id'])) {//对应公司加一
                Db::rollback();
                Err::add('操作失败请稍后尝试', RespCode::QUERY_ERR);
                Log::write("更新失败Company::addAgentNum->" . __LINE__, 'del_agent.log');
                return false;
            }
        } else {//门店
            if (!CompanyShop::addAgent($_company_shop_id, 1)) {//对门店加一
                Db::rollback();
                Err::add('操作失败请稍后尝试', RespCode::QUERY_ERR);
                Log::write("更新失败CompanyShop::addAgent->" . __LINE__, 'del_agent.log');
                return false;
            }
        }
        //删除经纪人
        $beishanchu = db("company_agent")
            ->where('id', $params['id'])
            ->field('phone,id')
            ->find();
        $new_phone = $beishanchu['phone'] . '_' . $beishanchu['id'];
        if (!db("company_agent")
            ->where('id', $params['id'])
            ->update(['deleted' => 1, 'phone' => $new_phone])) {
            Db::rollback();
            Err::add('操作失败请稍后尝试', RespCode::QUERY_ERR);
            Log::write("更新失败company_agent->" . __LINE__, 'del_agent.log');
            return false;
        }
        Db::commit();
        return true;
    }

}
